import {messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Alert, Button, Spin, Row, Col, Modal, InputNumber, message, Input, Timeline, Icon } from 'antd'
const TextArea = Input.TextArea;
import moment from 'moment'
import ImageUpload from 'components/image-upload'
import loanAndRefundService from 'containers/financial-management/loan-and-refund/loan-and-refund.service'
import 'styles/request/loan-request/repayment-detail-frame.scss'
import borrowService from "../borrow-and-return.service";

class RefundContent extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      oid: null,
      info: {},
      confirmAmountModalVisible: false, //确认还款金额弹框
      notReceivedModalVisible: false, //未收到弹框
      modalLoading: false, //弹框确认按钮loading
      repaymentAmount: 0, //财务确认还款金额
      copyRepaymentValue: 0,
      notReceivedReason: '未收到款项', //未收到内容
      printLoading: false,
      buttonRoleSwitch:this.checkPageRole('REPAYMENTSLIPMANAGEMENT', 2) && this.checkFunctionProfiles(['er.disabled'], [[false, undefined]]) && this.checkFunctionProfiles(['finance.audit.disabled'], [[false, undefined]]) //按钮操作权限
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.refundFrame === this.props.refundFrame){
      return -1;
    }
    if(!nextProps.refundFrame){
      this.setState({
        oid: null,
        info: {},
        repaymentAmount: 0,
        copyRepaymentValue: 0
      })
    }
    this.setState({
      oid: nextProps.refundParams
    },() => {
      this.getInfo()
    })
  }

  getInfo = () => {
    this.setState({ loading: true });
    loanAndRefundService.getRefundInfo(this.state.oid).then(res => {
      this.setState({
        loading: false,
        info: res.data,
        repaymentAmount: Number(res.data.repaymentValue),
        copyRepaymentValue: Number(res.data.repaymentValue)
      })
    }).catch(e => {
      // message.error(e.response.data.message);
      this.setState({loading:false});
    })
  };

  //获取还款历史状态
  getRefundStatus = (operation) => {
    let history = {};
    if (operation === 5000) {
      history.text = messages('request.key148'/*转账还款提交*/); //转账还款提交
      history.icon = "up-circle-o";
      history.color = "#4CA8BC"
    }
    if (operation === 5001) {
      history.text = messages('request.key149'/*现金还款提交*/); //现金还款提交
      history.icon = "up-circle-o";
      history.color = "#4CA8BC"
    }
    if (operation === 5002) {
      history.text = messages('request.key150'/*财务收款通过*/); //财务收款通过
      history.icon = "check-circle-o";
      history.color = "#5EBD93"
    }
    if (operation === 5003) {
      history.text = messages('request.key151'/*财务收款驳回*/); //财务收款驳回
      history.icon = "close-circle-o";
      history.color = "#E57670"
    }
    if (operation === 1002) {
      history.text = messages('request.key152'/*财务撤回还款*/); //财务撤回还款
      history.icon = "close-circle-o";
      history.color = "#E57670"
    }
    if (operation === 5013) {
      history.text = messages('request.key3151'/*转永久还款提交*/); //转永久还款提交
      history.icon = "up-circle-o";
      history.color = "#5EBD93"
    }
    return history
  };

  handleCancel = () => {
    this.props.close();
  };

  renderInfo = (title, info) => {
    let result = info ? info : '-';
    return (
      <div className="render-info">
        <div className="title">{title}</div>
        <div className="info">{result}</div>
      </div>
    )
  };

  //财务确认是否收到款
  handleConfirm = (value) => {
    const { repaymentAmount, copyRepaymentValue } = this.state;
    if (value === 'PASS' && !repaymentAmount) {
      message.error(messages('request.key153'/*请输入还款金额*/))
    } else {
      let params = {
        repaymentOid: this.state.oid,
        reason:value === 'PASS' ? null : this.state.notReceivedReason,
        currencyCode: this.state.info.curreny,
        repaymentAmount: value === 'PASS' ? repaymentAmount : copyRepaymentValue,
        result: value
      };
      this.setState({ modalLoading: true });
      if (value === 'REJECT' && this.state.info.remark === '公务卡转因私代还款数据, 系统自动生成') {
        loanAndRefundService.bankBillRepaymentReject(params).then(() => {
          this.setState({
            modalLoading: false,
            confirmAmountModalVisible: false,
            notReceivedModalVisible: false,
          });
          this.props.close(true);
          message.success(messages('common.operate.success'));
        }).catch(e => {
          this.setState({ modalLoading: false });
          message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
        });
        return true
      }
      loanAndRefundService.confirmReceipt(params).then(() => {
        this.setState({
          modalLoading: false,
          confirmAmountModalVisible: false,
          notReceivedModalVisible: false,
        });
        this.props.close(true);
        message.success(messages('common.operate.success'));
      }).catch(e => {
        this.setState({ modalLoading: false });
        message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
      })
    }
  };

  //财务确认撤回弹框
  showConfirm = () => {
    Modal.confirm({
      title: messages('request.key154'/*确认撤回还款*/),
      content: messages('request.key155'/*将删除该条还款记录，并通知员工*/),
      okText: messages('request.key156'/*删除并通知员工*/),
      cancelText: messages('common.back'),
      iconType: 'exclamation-circle',
      onOk: this.handleCallBack
    })
  };

  //撤回
  handleCallBack = () => {
    let params = {
      reason: messages('request.key152'/*财务撤回还款*/),
      repaymentOid: this.state.oid
    };
    loanAndRefundService.callBackRefund(params).then(() => {
      message.success(messages('common.operate.success'));
      this.handleCancel();
      this.props.close(true)
    })
  };

  //财务确认收款金额
  handleConfirmAmount = () => {
    this.setState({ confirmAmountModalVisible: true }, () => {
      this.setState({ repaymentAmount: Number(this.state.info.repaymentValue) })
    })
  };

  handlePrint = () => {
    const { info } = this.state;
    this.setState({ printLoading: true });
    borrowService.printRepayment(info.repaymentOid).then(res => {
      this.setState({ printLoading: false });
      window.open(res.data.link, '_blank')
    }).catch(e => {
      this.setState({ printLoading: false });
      message.error(e.response.data.message);
    });
  };

  render() {
    const { loading, info, confirmAmountModalVisible, modalLoading, repaymentAmount, notReceivedModalVisible,
      buttonRoleSwitch, printLoading } = this.state;
    let actRepayAmount = info.actRepayAmount || info.repaymentValue;
    let alertContent = (
      <div className="alert-content-warn">
        {info.status === '1001' && <div>{messages('request.key157'/*等待财务确认*/)}…</div>}
        {info.status === '1002' && (
          <div>
            {moment(info.updateDate || info.createDate).format('YYYY-MM-DD HH:mm')} {info.financeName}-{info.financeID} {info.isFinance ?
            messages('request.key158'/*创建还款记录*/) : messages('request.key159'/*确认收款*/)}
          </div>
        )}
        {info.status === '1003' && <div>{moment(info.createdDate).format('YYYY-MM-DD HH:mm')} {info.title}</div>}
        <div>
          {messages('request.key123'/*日期*/)}：{moment(info.createDate).format('YYYY-MM-DD')}
          <span className="ant-divider"/>
          {messages('request.key124'/*还款单号*/)}：{info.businessCode}
          <span className="ant-divider"/> {messages('loan-billing.key2')/*借款行号*/}：{info.loanLineNumber}
          <span className="ant-divider"/>
          {messages('request.key125'/*还款方式*/)}：{info.isFinance ? messages('request.key126'/*财务创建*/) :
            info.type === '0' ? messages('request.key127'/*现金还款*/) :
            info.type === '1' ? messages('request.key128'/*转账还款*/) : messages('request.key129'/*报销单还款*/)
          }
          <span className="ant-divider"/>
          {messages('request.key6'/*当前状态*/)}：{info.status === '1001' ? messages('request.key119'/*还款中*/) :
          info.status === '1002' ? messages('request.key118'/*已还款*/) : messages('request.key132'/*被驳回*/)}
          <span className="ant-divider"/> {messages('loan-billing.key104')/*支付流水号*/}：{info.cashTransactionDetailLogDTO ? info.cashTransactionDetailLogDTO.transactionDetailCode : '-'}
        </div>
      </div>
    );
    return(
      <div className="repayment-detail-frame">
        {info.status && (
          <Alert message={info.status === '1001' ? messages('request.key119'/*还款中*/) :
            info.status === '1002' ? `${messages('request.key131'/*还款金额*/)}：${info.curreny} ${this.filterMoney(actRepayAmount,queryCurrencyPrecision(info.curreny),true)}` :
              messages('request.key132'/*被驳回*/)}
                 description={alertContent}
                 type={info.status === '1001' ? 'warning' : info.status === '1002' ? 'success' : 'error'}
                 className="alert-info"
                 showIcon/>
        )}
        <Spin spinning={loading}>
          {info.type !== '0' && (
            <div className="refund-info">
              <Row>
                <Col span={12}><h4>{messages('request.key135'/*还款方信息*/)}</h4></Col>
                <Col span={11} offset={1}><h4>{messages('request.key143'/*收款方信息*/)}</h4></Col>
              </Row>
              <Row>
                <Col span={12}>{this.renderInfo(messages('request.key138'/*开户名*/), info.payAccountName)}</Col>
                <Col span={11} offset={1}>{this.renderInfo(messages('request.key138'/*开户名*/), info.acceptAccountName)}</Col>
              </Row>
              <Row>
                <Col span={12}>{this.renderInfo(messages('request.key139'/*开户账号*/), info.payAccount)}</Col>
                <Col span={11} offset={1}>{this.renderInfo(messages('request.key139'/*开户账号*/), info.acceptAccount)}</Col>
              </Row>
              <Row>
                <Col span={12}>{this.renderInfo(messages('request.key140'/*开户银行*/), info.payBankName)}</Col>
                <Col span={11} offset={1}>{this.renderInfo(messages('request.key140'/*开户银行*/), info.acceptBankName)}</Col>
              </Row>
              <Row>
                <Col span={12}>
                  {this.renderInfo(messages('request.key131'/*还款金额*/),
                    (info.curreny || '') + ' ' + this.filterMoney(info.repaymentValue,queryCurrencyPrecision(info.curreny),true))}
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  {this.renderInfo(messages('request.key141'/*银行回单号*/),info.bankReceiptNumber)}
                </Col>
              </Row>
              {info.status === '1002' && (
                <Row className="confirm-amount">
                  <Col span={12}>
                    {this.renderInfo(messages('request.key160'/*确认还款金额*/),
                      (info.curreny || '') + ' ' + this.filterMoney(actRepayAmount,queryCurrencyPrecision(info.curreny),true))}
                  </Col>
                </Row>
              )}
            </div>
          )}
          <div className="remark-info">
            <h4>{messages('common.remark')}：</h4>
            <div>{info.remark || '-'}</div>
          </div>
          <Row className="remark-info">
            {info.repayAttchment && (
              <ImageUpload defaultFileList={info.repayAttchment}
                           key={info.businessCode}
                           attachmentType="INVOICE_IMAGES"
                           disabled/>
            )}
          </Row>
          <div className="approvals refund-history">
            <h4>{messages('request.key161'/*还款历史*/)}</h4>
            <Timeline>
              {info.approvalHistoryDTOs && info.approvalHistoryDTOs.map(item => {
                return (
                  <Timeline.Item key={item.id}
                                 dot={<Icon type={this.getRefundStatus(item.operation).icon} style={{color: this.getRefundStatus(item.operation).color}}/>}>
                    <Row>
                      <Col span={7}>{moment(item.createdDate).format('YYYY-MM-DD HH:mm')}</Col>
                      <Col span={7} className="operation-type">{this.getRefundStatus(item.operation).text}</Col>
                      <Col span={10} className="operation-name">{item.currentApplicant ? (item.operator.userOID === item.currentApplicant.userOID ? item.operator.fullName + ' ' + item.operator.employeeID : `${item.currentApplicant.fullName + ' ' + item.currentApplicant.employeeID}(${item.operator.fullName + ' ' + item.operator.employeeID} 代提交)`) : item.operator.fullName + ' ' + item.operator.employeeID}</Col>
                    </Row>
                    <Row style={{color: item.operation === 5003 ? '#E57670' : '#666'}}>{item.operationDetail}</Row>
                  </Timeline.Item>
                )
              })}
            </Timeline>
          </div>
        </Spin>

        {this.props.location.pathname.indexOf('loan-and-refund') > -1 && info.status === '1001' && buttonRoleSwitch? (
          <div className="slide-footer">
            <Button type="primary" onClick={this.handleConfirmAmount}>
              {messages('request.key159'/*确认收款*/)}
            </Button>
            {/* <Button onClick={this.handlePrint} loading={printLoading} type='primary'>{messages('common.print')}</Button> */}
            <Button onClick={() => this.setState({notReceivedModalVisible: true})} type={'primary'}>{messages('request.key162'/*未收到*/)}</Button>
          </div>
        ) : (
          info.isFinance && info.status === '1002' && buttonRoleSwitch ? (
            <div className="slide-footer">
              {/* {
                this.props.location.pathname.indexOf('loan-and-refund') > -1 &&
                <Button onClick={this.showConfirm}>{messages('request.key163')}</Button>
              } */}
              {/* <Button onClick={this.handlePrint} loading={printLoading} type='primary'>{messages('common.print')}</Button> */}
              <Button onClick={this.handleCancel}>{messages('request.key102'/*关闭*/)}</Button>
            </div>
          ) : (
            <div className="slide-footer">
              {/* <Button onClick={this.handlePrint} loading={printLoading} type='primary'>{messages('common.print')}</Button> */}
              <Button onClick={this.handleCancel}>{messages('request.key102'/*关闭*/)}</Button>
            </div>
          )
        )}

        <Modal visible={confirmAmountModalVisible}
               confirmLoading={modalLoading}
               onOk={() => this.handleConfirm('PASS')}
               onCancel={() => this.setState({confirmAmountModalVisible: false})}
               okText={messages('finance-setting.key137'/*确认*/)}
               title={messages('request.key160'/*确认还款金额*/)}>
          <div>
            {!this.props.profile['finance.modify.repayment.money.disabled'] && false && (
              <div>{messages('request.key165'/*如实际还款和申请不符，可在下方修改金额*/)}</div>
            )}
            {messages('request.key166'/*金额*/)}{info.curreny ? `（${info.curreny}）` : ''}：
            <InputNumber min={0}
                         max={Number(Number(info.repaymentValue).toFixed(queryCurrencyPrecision(info.curreny)))}
                         value={repaymentAmount}
                         precision={queryCurrencyPrecision(info.curreny)}
                         formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        //  disabled={this.props.profile['finance.modify.repayment.money.disabled']}
                         disabled={true}
                         onChange={value => this.setState({repaymentAmount: value})}
                         style={{width:'60%',marginTop:20}}/>
          </div>
        </Modal>

        <Modal visible={notReceivedModalVisible}
               confirmLoading={modalLoading}
               onOk={() => this.handleConfirm('REJECT')}
               onCancel={() => this.setState({notReceivedModalVisible: false})}
               okText={messages('request.key164'/*确认并通知员工*/)}
               title={messages('request.key167'/*输入内容*/)}>
          <div>
            <TextArea rows={3}
                      placeholder={messages('request.key168'/*如不输入，默认理由：未收到款项*/)}
                      style={{resize: 'none'}}
                      onChange={e => this.setState({notReceivedReason: e.target.value})}/>
          </div>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
  }
}

const wrappedRefundContent = Form.create()(RefundContent);

export default connect(mapStateToProps)(wrappedRefundContent)
